﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Nette.Utils
{
    class FileTool
    {
        public static Encoding encoding = Encoding.UTF8;
        public static void WriteStringArray(List<string> strList,String path,Encoding encoding)
        {
            using(FileStream fs = new FileStream(path, FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs, encoding))
                {
                    strList.ForEach((val) => {
                        sw.Write(val);
                    });
                }
            }
        }

        public static List<String> ReaderStringArray(String path, Encoding encoding)
        {
            List<String> strs = new List<String>();
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs, encoding))
                {
                    string temp;
                    while (null != (temp = sr.ReadLine()))
                    {
                        strs.Add(temp);
                    }
                }
            }
            return strs;
        }


        public static void WriteObject(object obj,String path)
        {
            JObject jObject = JObject.FromObject(obj);

            FileInfo fileInfo = new FileInfo(path);
            if (!Directory.Exists(fileInfo.DirectoryName))
            {
                Directory.CreateDirectory(fileInfo.DirectoryName);
            }
            using (FileStream fs = new FileStream(path,FileMode.Create,FileAccess.Write)) 
            {
                using (StreamWriter sw = new StreamWriter(fs)) 
                {
                    jObject.WriteTo(new JsonTextWriter(sw));
                }
            }
        }

        public static T? ReadObject<T>(string path)
        {
            if (!File.Exists(path))return default(T);

            using (FileStream fs = File.OpenRead(path))
            {
                using (StreamReader sw = new StreamReader(fs))
                {
                    JToken jToken = JObject.ReadFrom(new JsonTextReader(sw));
                    return jToken.ToObject<T>();
                }
            }
        }
    }
}
